import { UserModel, type User } from "../db/model";
import * as bcrypt from "bcrypt";
import * as jwt from "jsonwebtoken";
import { Context } from "hono";

const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";

interface JwtPayload {
  userId: string;
  email: string;
  exp?: number;
  iat?: number;
}

export class AuthService {
  async register(data: {
    email: string;
    password: string;
    username: string;
    gender?: string;
    description?: string;
    birthdayAt?: Date;
  }) {
    const existingUser = await UserModel.findOne({ email: data.email });
    if (existingUser) {
      throw new Error("邮箱已被注册");
    }

    const hashedPassword = await bcrypt.hash(data.password, 10);
    const user = await UserModel.create({
      ...data,
      password: hashedPassword,
    });

    const token = jwt.sign(
      { userId: user._id.toString(), email: user.email },
      JWT_SECRET,
      { expiresIn: "24h" }
    );

    return {
      token,
      user: {
        _id: user._id.toString(),
        email: user.email,
        username: user.username,
        gender: user.gender,
        description: user.description,
        birthdayAt: user.birthdayAt,
        createdAt: user.createdAt
      }
    };
  }

  async login(data: { email: string; password: string }) {
    const user = await UserModel.findOne({ email: data.email });
    if (!user) {
      throw new Error("用户不存在");
    }

    const isValid = await bcrypt.compare(data.password, user.password);
    if (!isValid) {
      throw new Error("密码错误");
    }

    const token = jwt.sign(
      { userId: user._id.toString(), email: user.email },
      JWT_SECRET,
      { expiresIn: "24h" }
    );

    return {
      token,
      user: {
        _id: user._id.toString(),
        email: user.email,
        username: user.username,
        gender: user.gender || undefined,
        description: user.description || undefined,
        birthdayAt: user.birthdayAt || undefined,
        createdAt: user.createdAt || new Date()
      }
    };
  }

  async updateUser(userId: string, data: Partial<User>) {
    const user = await UserModel.findByIdAndUpdate(
      userId,
      { $set: data },
      { new: true }
    );
    if (!user) {
      throw new Error("用户不存在");
    }
    return {
      _id: user._id.toString(),
      email: user.email,
      username: user.username,
      gender: user.gender || undefined,
      description: user.description || undefined,
      birthdayAt: user.birthdayAt || undefined,
      createdAt: user.createdAt || new Date()
    };
  }

  async getUserById(userId: string) {
    const user = await UserModel.findById(userId);
    if (!user) {
      throw new Error("用户不存在");
    }
    return {
      _id: user._id.toString(),
      email: user.email,
      username: user.username,
      gender: user.gender || undefined,
      description: user.description || undefined,
      birthdayAt: user.birthdayAt || undefined,
      createdAt: user.createdAt || new Date()
    };
  }

  async deleteUser(userId: string) {
    const result = await UserModel.findByIdAndDelete(userId);
    if (!result) {
      throw new Error("用户不存在");
    }
    return true;
  }

  async logout(c: Context) {
    c.header("Authorization", "");
    return true;
  }
}
